package com.maz.androidprojectcomponenttest.fragment;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.LoginButton;
import com.maz.androidprojectcomponenttest.R;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class FacebookFragment extends Fragment implements OnClickListener, Session.StatusCallback, Request.Callback{
	
	private final static String TAG = FacebookFragment.class.getName();
	private final static String PUBLISH_PERMISSION = "publish_actions";

    private View fragmentView;
	private Button shareButton;
	private UiLifecycleHelper uiLifeCycle;
	private LoginButton loginButton;
	private boolean pendingReauthorization;
	
	private List<String> permissions;;
	
	public FacebookFragment(){
		permissions = Arrays.asList(PUBLISH_PERMISSION);
		pendingReauthorization = false;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		uiLifeCycle = new UiLifecycleHelper(getActivity(), this);
		uiLifeCycle.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		initLayout(inflater, container, savedInstanceState);
		initComponents();
		return fragmentView;
	}
	
	private void initLayout(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState){
		fragmentView = inflater.inflate(R.layout.fragment_facebook, null);
		shareButton = (Button) fragmentView.findViewById(R.id.shareButton);
		loginButton = (LoginButton) fragmentView.findViewById(R.id.authButton);
	}
	
	private void initComponents(){
		loginButton.setFragment(this);
		shareButton.setOnClickListener(this);
	}
	
	private void manualTriggerSessionStateChange(){
		Session session = Session.getActiveSession();
		
		if(session!=null && (session.isOpened() || session.isClosed())){
			handleStateChange(session, session.getState(), null);
		}
		
	}
	
	private void handleStateChange(Session mSession, SessionState mSessionState, Exception mException){
		if(mSessionState.isOpened()){
			shareButton.setVisibility(View.VISIBLE);
		}else if(mSessionState.isClosed()){
			shareButton.setVisibility(View.GONE);
		}
	}
	
	private void publishStory(){
		Session session = Session.getActiveSession();
		if(session != null){
			if(checkPermission(session)){
				return;
			}
			sendPostRequest(session);
		}
	}
	
	private boolean checkPermission(Session mSession){
		List<String> sessionPermissions = mSession.getPermissions();
		if(!isSubsetOf(permissions, sessionPermissions)){
			pendingReauthorization = true;
			Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this, permissions);
			mSession.requestNewPublishPermissions(newPermissionsRequest);
			return true;
		}
		return false;
	}
	
	private Bundle preparePostParameters(){
		Bundle bundle = new Bundle();
        bundle.putString("message", "Picture testing");
		/*bundle.putString("name", "This is a testing Post");
		bundle.putString("caption", "Well as above caption for the testing Post");
		bundle.putString("description", "the description for the testing post");
		bundle.putString("link", "www.google.com");      */
        Bitmap postPictureBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.url);
        ByteArrayOutputStream imageOutPuteStream = new ByteArrayOutputStream();
        postPictureBitmap.compress(Bitmap.CompressFormat.JPEG, 100, imageOutPuteStream);
        byte[] data = imageOutPuteStream.toByteArray();
		bundle.putByteArray("picture", data);
		return bundle;
	}
	
	private void sendPostRequest(Session mSession){
        /*
        For stories, use "me/feed"
         */
		Request request = new Request(mSession, "me/photos", preparePostParameters(), HttpMethod.POST, this);
		RequestAsyncTask requestAsyncTask = new RequestAsyncTask(request);
		requestAsyncTask.execute();
	}
	private boolean isSubsetOf(Collection<String> mSubset, Collection<String> mSuperset){
		for(String eachString : mSubset){
			if(!mSuperset.contains(eachString)){
				return false;
			}
		}
		return true;
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		uiLifeCycle.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiLifeCycle.onDestroy();
	}

	@Override
	public void onPause() {
		super.onPause();
		uiLifeCycle.onPause();
	}

	@Override
	public void onResume() {
		super.onResume();
		manualTriggerSessionStateChange();
		uiLifeCycle.onResume();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		uiLifeCycle.onSaveInstanceState(outState);
	}

	@Override
	public void onClick(View v) {
		if(v.getId() == shareButton.getId()){
			publishStory();
		}
	}

    @Override
    public void call(Session session, SessionState state, Exception exception) {
        handleStateChange(session, state, exception);
    }

    @Override
    public void onCompleted(Response response) {
        JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
        String postID = "";
        try {
            postID = graphResponse.getString("id");
        } catch (JSONException e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
        FacebookRequestError error = response.getError();
        if(error!=null){
            Toast.makeText(getActivity(), error.getErrorMessage(), Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(getActivity(), postID, Toast.LENGTH_LONG).show();
        }
    }

	/*
	 * TODO:
	 * Learn how to:
	 * 1. Publish status and links on timeline.    done
	 * 2. Publish images (such as screen capture) to user timeline.           done
	 * 3. Complete by implementing 
	 * 4. Find out how to post picture from local storage and not URL. Probably use PICTURE but instead of putting URL put the picture base64 encoded string?        done
	 */
}	
